/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uy.edu.ort.ws.cliente;

import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Properties;
import javax.swing.JOptionPane;
import uy.edu.ort.dominio.Fuente;
import uy.edu.ort.dominio.ListaTopicos;
import uy.edu.ort.dominio.ManejoJSON;
import uy.edu.ort.dominio.Noticia;
import uy.edu.ort.recepcionar.fuente.RecepcionarDatosDeFuenteWS;
import uy.edu.ort.recepcionar.fuente.RecepcionarDatosDeFuenteWS_Service;

/**
 *
 * @author Administrador
 */
public class VentanaFuente extends javax.swing.JFrame {

    private static URL url = null;
    private static int idNoticia = 1;

    /**
     * Creates new form VentanaFuente
     */
    public VentanaFuente() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtIdFuente = new javax.swing.JTextField();
        txtCodigo = new javax.swing.JTextField();
        cboTopico = new javax.swing.JComboBox();
        btnConsultar = new javax.swing.JButton();
        txtTitulo = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtContenido = new javax.swing.JTextArea();
        btnEnviar = new javax.swing.JButton();
        lblMensaje = new javax.swing.JLabel();
        lblTitulo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Aplicación Cliente Fuente");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Id Fuente");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 75, 57, -1));
        jLabel1.getAccessibleContext().setAccessibleName("lblFuenteID");

        jLabel2.setText("Codigo");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 106, -1, -1));
        jLabel2.getAccessibleContext().setAccessibleName("lblCodAutoriza");

        jLabel3.setText("Topico");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 138, -1, -1));
        jLabel3.getAccessibleContext().setAccessibleName("lblTopico");

        jLabel4.setText("Titulo");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 171, -1, -1));
        jLabel4.getAccessibleContext().setAccessibleName("lblTitulo");

        jLabel5.setText("Contenido");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 206, -1, -1));
        jLabel5.getAccessibleContext().setAccessibleName("lblContenido");

        txtIdFuente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtIdFuenteKeyReleased(evt);
            }
        });
        getContentPane().add(txtIdFuente, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 72, 116, -1));
        txtIdFuente.getAccessibleContext().setAccessibleName("txtIdFuente");

        getContentPane().add(txtCodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 103, 116, -1));
        txtCodigo.getAccessibleContext().setAccessibleName("txtCodigo");

        getContentPane().add(cboTopico, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 135, 116, -1));
        cboTopico.getAccessibleContext().setAccessibleName("cboTopico");

        btnConsultar.setText("Consultar Topicos");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });
        getContentPane().add(btnConsultar, new org.netbeans.lib.awtextra.AbsoluteConstraints(226, 134, 144, -1));
        btnConsultar.getAccessibleContext().setAccessibleName("btnConsultar");

        txtTitulo.setEditable(false);
        getContentPane().add(txtTitulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 168, 116, -1));
        txtTitulo.getAccessibleContext().setAccessibleName("txtTitulo");

        txtContenido.setEditable(false);
        txtContenido.setColumns(20);
        txtContenido.setRows(5);
        jScrollPane1.setViewportView(txtContenido);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(96, 206, -1, -1));
        jScrollPane1.getAccessibleContext().setAccessibleName("txtContenido");

        btnEnviar.setText("Enviar Noticia");
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });
        getContentPane().add(btnEnviar, new org.netbeans.lib.awtextra.AbsoluteConstraints(96, 313, 166, 26));
        btnEnviar.getAccessibleContext().setAccessibleName("btnEnviar");

        lblMensaje.setForeground(new java.awt.Color(255, 0, 0));
        getContentPane().add(lblMensaje, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 350, 298, 22));

        lblTitulo.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
        lblTitulo.setForeground(new java.awt.Color(0, 102, 204));
        lblTitulo.setText("Envio de Noticias");
        getContentPane().add(lblTitulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 21, 162, 33));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-403)/2, (screenSize.height-423)/2, 403, 423);
    }// </editor-fold>//GEN-END:initComponents

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        // TODO add your handling code here:
        if (!txtIdFuente.getText().isEmpty()) {
            if (url != null) {
                RecepcionarDatosDeFuenteWS service = (RecepcionarDatosDeFuenteWS) new RecepcionarDatosDeFuenteWS_Service(url).getRecepcionarDatosDeFuenteWSPort();
                //Creo objeto Fuente, lo paso a JSON y la mando por web services
                Fuente fuente = new Fuente(Long.valueOf(txtIdFuente.getText()), txtCodigo.getText());

                ManejoJSON mj = new ManejoJSON();
                String identificacion = mj.ObjetoToJSON(fuente);
                //System.out.println("LLEGAAAAAA CLIENTEEE");
                //obtener topicos de WS
                String topicos = service.consultarTopicos(identificacion);
                System.out.println("Topicos: " + topicos);
                lblMensaje.setText("Topicos: " + topicos);
                cboTopico.removeAllItems();
                if (!topicos.equals("Fuente inválida")) {

                    ListaTopicos lista = new ListaTopicos();
                    lista = mj.JSONToListaTopicos(topicos);

                    Iterator<String> iterador = lista.getLista().iterator();

                    while (iterador.hasNext()) {
                        cboTopico.addItem(iterador.next().toString());
                    }

                    txtTitulo.setEditable(true);
                    txtContenido.setEditable(true);
                    btnEnviar.setEnabled(true);


                } else {

                    lblMensaje.setText("Fuente no autorizada, intente nuevamente.");
                    txtIdFuente.setText("");
                    txtCodigo.setText("");
                    txtIdFuente.selectAll();
                }


            } else {
                System.out.println("No se pudo obtener correctamente la URL");
                lblMensaje.setText("No se pudo obtener correctamente la URL");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe ingresar un Id de Fuente.", "Atención", JOptionPane.INFORMATION_MESSAGE);
        }

    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
        // TODO add your handling code here:
        if (!txtIdFuente.getText().isEmpty()) {
           if (url != null) {
                RecepcionarDatosDeFuenteWS service = (RecepcionarDatosDeFuenteWS) new RecepcionarDatosDeFuenteWS_Service(url).getRecepcionarDatosDeFuenteWSPort();

                //Creo objeto Noticia, lo paso a JSON y la mando por web services
                String topico = "";
                if (cboTopico.getSelectedItem() != null){
                    topico = cboTopico.getSelectedItem().toString();
                }
                    
                
                Noticia noticia = new Noticia(idNoticia, txtIdFuente.getText(), txtCodigo.getText(), txtTitulo.getText(), txtContenido.getText(), topico);


                ManejoJSON mj = new ManejoJSON();
                String noti = mj.ObjetoToJSON(noticia);

                //probando metodo mandar noticia de WS
                String confirmacion = service.recibirNoticia(noti);
                lblMensaje.setText(confirmacion);
                idNoticia += 1;
                //System.out.println("Confirmacion: " + confirmacion);

            } else {
                System.out.println("No se pudo obtener correctamente la URL");
                lblMensaje.setText("No se pudo obtener correctamente la URL");
            } 
        }
        else {
            JOptionPane.showMessageDialog(null, "Debe ingresar un Id de Fuente.", "Atención", JOptionPane.INFORMATION_MESSAGE);
        }
        
    }//GEN-LAST:event_btnEnviarActionPerformed

    private void txtIdFuenteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIdFuenteKeyReleased
        // TODO add your handling code here:
        String str = txtIdFuente.getText();

        char[] fuente = str.toCharArray();

        char[] resultado = new char[fuente.length];

        int j = 0;

        boolean error = false;

        for (int i = 0; i < fuente.length; i++) {

            if(fuente[i]>='0' && fuente[i]<='9')
                resultado[j++] = fuente[i];   
            else{
                error = true;
                java.awt.Toolkit.getDefaultToolkit().beep();
            }
        }
        if(error){
            txtIdFuente.setText("");
            txtIdFuente.setText(new String(resultado,0,j));
        }
        
    }//GEN-LAST:event_txtIdFuenteKeyReleased

    //Métodos para verificar que campos sean correctos
    private boolean ChequearCamposConsultaTopicos()
    {
        return !txtIdFuente.toString().isEmpty() && !txtCodigo.toString().isEmpty();
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                

}
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class  

.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 

catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class  

.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 

catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class  

.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 

catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class  

.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaFuente().setVisible(true);
            }
        });
        
        

        //url = new URL("http://localhost:8080/ServiciosAgenciaWS/ServiciosAgenciaWS?wsdl");
        //Leo la URL desde el archivo de configuración
        try {
            LeerArchivo archivoPropiedades = new LeerArchivo();
            Properties prop = archivoPropiedades.getArchivoProperties();
            try {
                url = new URL(archivoPropiedades.getProperty(prop, "URL"));
            } catch (Exception e) {
                System.out.println("No se encuentra la clave URL en el archivo de propiedades");
                
            }
        } catch (Exception ee) {
            System.out.println("No se puede abrir el archivo properties");
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnEnviar;
    private javax.swing.JComboBox cboTopico;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMensaje;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextArea txtContenido;
    private javax.swing.JTextField txtIdFuente;
    private javax.swing.JTextField txtTitulo;
    // End of variables declaration//GEN-END:variables
}
